package gw.com.android.ui.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Region;
import android.support.annotation.ColorInt;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jett
 * @since 2017-12-11.
 */
public class GuideView extends RelativeLayout {

    private List<View> list;

    private int color = 0x88000000;
    private int leftOsmosis;
    private int topOsmosis;
    private int rightOsmosis;
    private int bottomOsmosis;

    public GuideView(Context context) {
        super(context);
        init();
    }

    public GuideView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GuideView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setWillNotDraw(false);
    }

    public void addUncoverView(View view) {
        if (view == null) {
            return;
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(view);
    }

    public void setCoverColor(@ColorInt int color) {
        this.color = color;
    }

    public void setOsmosis(int leftOsmosis, int topOsmosis, int rightOsmosis, int bottomOsmosis) {
        this.leftOsmosis = leftOsmosis;
        this.topOsmosis = topOsmosis;
        this.rightOsmosis = rightOsmosis;
        this.bottomOsmosis = bottomOsmosis;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (list != null && !list.isEmpty()) {
            canvas.save();
            canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight());
            for (View view : list) {
                if (view == null) {
                    continue;
                }
                int left = view.getLeft();
                int top = view.getTop();
                int right = view.getRight();
                int bottom = view.getBottom();
                left += leftOsmosis;
                top += topOsmosis;
                right -= rightOsmosis;
                bottom -= bottomOsmosis;
                canvas.clipRect(left, top, right, bottom, Region.Op.DIFFERENCE);
            }
            canvas.drawColor(color);
            canvas.restore();
        }
        super.onDraw(canvas);
    }

}
